package com.example.demo.socket;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Component
@ServerEndpoint(value = "/websocket/{sid}")
@Slf4j
public class WebSocketServer {

    /**
     * 记录当前在线连接数
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放所有在线的客户端
     */
    private static final Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        sendMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    public static void reportMsg(String message, String email, String name) {
        ReportMsg reportMsg = new ReportMsg(message, email, name);
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            log.info("服务端给客户端[{}] 发送消息对象 {}", toSession.getId(), reportMsg.getMsg());
            try {
                toSession.getBasicRemote().sendText(new Gson().toJson(reportMsg));
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    public static void screenInfoMsg(String message, Object... args) {
        ScreenMsg screenMsg = new ScreenMsg("log", String.format(message, args));
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            log.info("服务端给客户端[{}] 发送消息对象 {}", toSession.getId(), screenMsg.getMsg());
            try {
                toSession.getBasicRemote().sendText(new Gson().toJson(screenMsg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void screenWarnMsg(String message, Object... args) {
        ScreenMsg screenMsg = new ScreenMsg("warn", String.format(message, args));
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            log.info("服务端给客户端[{}] 发送消息对象 {}", toSession.getId(), screenMsg.getMsg());
            try {
                toSession.getBasicRemote().sendText(new Gson().toJson(screenMsg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void screenErrorMsg(String message, Object... args) {
        ScreenMsg screenMsg = new ScreenMsg("error", String.format(message, args));
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            log.info("服务端给客户端[{}] 发送消息对象 {}", toSession.getId(), screenMsg.getMsg());
            try {
                toSession.getBasicRemote().sendText(new Gson().toJson(screenMsg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 群发消息 排除自己
     *
     * @param message 消息内容
     */
    private void sendMessage(String message, Session fromSession) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            // 排除掉自己
            /* if (!fromSession.getId().equals(toSession.getId())) {*/
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getAsyncRemote().sendText(message);
            /*  }*/
        }
    }
}
